package com.k2.gulimall.auth.controller;


import com.alibaba.fastjson.TypeReference;
import com.k2.common.exception.BizCodeEnume;
import com.k2.common.utils.NewData;
import com.k2.common.utils.R;
import com.k2.common.vo.MemberVo;
import com.k2.common.vo.UserRegisterVo;
import com.k2.gulimall.auth.service.MemberService;
import com.k2.gulimall.auth.service.ThirdPartFeignService;
import com.k2.gulimall.member.entity.MemberEntity;
import com.k2.gulimall.member.entity.MemberLevelEntity;
import com.k2.gulimall.member.entity.MemberLoginLogEntity;
import com.k2.gulimall.member.entity.MemberStatisticsInfoEntity;
import com.k2.common.constant.AuthServerConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.apache.commons.lang.StringUtils;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.k2.common.constant.AuthServerConstant.LOGIN_USER;

@Controller
public class LoginController {

    @Autowired
    MemberService memberService;
    @Autowired
    private ThirdPartFeignService thirdPartFeignService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    NewData newData = new NewData();

    @ResponseBody
    @GetMapping(value = "/sms/sendCode")
    public R sendCode(String phone) {
        //1、接口防刷
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            //活动存入redis的时间，用当前时间减去存入redis的时间，判断用户手机号是否在60s内发送验证码
            long currentTime = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - currentTime < 60000) {
                //60s内不能再发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //2、验证码的再次效验 redis.存key-phone,value-code
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        String codeNum = String.valueOf(code);
        String redisStorage = codeNum + "_" + System.currentTimeMillis();
        //存入redis，防止同一个手机号在60秒内再次发送验证码
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,
                redisStorage,10, TimeUnit.MINUTES);
        if (thirdPartFeignService.sendCode(phone, codeNum)==0){
            return R.ok();
        }else {
            return R.error();
        }
    }


    /**
     *
     * TODO: 重定向携带数据：利用session原理，将数据放在session中。
     * TODO:只要跳转到下一个页面取出这个数据以后，session里面的数据就会删掉
     * TODO：分布下session问题
     * RedirectAttributes：重定向也可以保留数据，不会丢失
     * 用户注册
     * @return
     */
    @PostMapping(value = "/register")
    public String register(@Valid UserRegisterVo vos, BindingResult result,
                           RedirectAttributes attributes) {
        //如果有错误回到注册页面
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors",errors);
            //效验出错回到注册页面
            return "redirect:http://localhost:20000/reg.html";
        }
        //1、效验验证码
        String code = vos.getCode();
        //获取存入Redis里的验证码
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
        if (!StringUtils.isEmpty(redisCode)) {
            //截取字符串
            if (code.equals(redisCode.split("_")[0])) {
                //删除验证码;令牌机制
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vos.getPhone());
                //验证码通过，真正注册，调用远程服务进行注册
                MemberEntity memberEntity = new MemberEntity();
                //用户名
                memberEntity.setUsername(vos.getUserName());
                //密码进行MD5加密
                BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
                String encode = bCryptPasswordEncoder.encode(vos.getPassword());
                memberEntity.setPassword(encode);
                //手机号
                memberEntity.setMobile(vos.getPhone());
                //默认的会员等级
                memberEntity.setLevelId(memberService.getMemberLevelToDefault().getData(new TypeReference<MemberLevelEntity>(){}).getId());
                //默认成长值
                memberEntity.setGrowth(0);
                //默认积分
                memberEntity.setIntegration(0);
                //用户昵称
                memberEntity.setNickname(vos.getUserName());
                //用户启用状态
                memberEntity.setStatus(0);
                //会员创建时间
                memberEntity.setCreateTime(newData.getNewData());

                R register = memberService.savemember(memberEntity);
                if (register.getCode() == 0) {
                    //添加统计信息
                    memberService.addmemberLoginLog(vos);
                    //成功
                    return "redirect:http://localhost:20000/login.html";
                } else {
                    //失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", register.getData(new TypeReference<String>(){}));
                    attributes.addFlashAttribute("errors",errors);
                    return "redirect:http://localhost:20000/reg.html";
                }
            } else {
                //效验出错回到注册页面
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://localhost:20000/reg.html";
            }
        } else {
            //效验出错回到注册页面
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://localhost:20000/reg.html";
        }
    }

    @GetMapping(value = "/login.html")
    public String loginPage(HttpSession session) {
        //从session先取出来用户的信息，判断用户是否已经登录过了
        Object attribute = session.getAttribute(LOGIN_USER);
        //如果用户没登录那就跳转到登录页面
        if (attribute == null) {
            return "login";
        } else {
            return "redirect:http://localhost:10000/index.html";
        }
    }

    /**
     * 会员微博或微信登陆时，把会员的Ip和地址添加到session中，方便之后添加会员的登陆信息
     * @param userRegisterVo
     * @param session
     */
    @RequestMapping("/addSessionIp")
    public void addSessionIp(UserRegisterVo userRegisterVo,HttpSession session){
        session.setAttribute("userIp",userRegisterVo);

    }


    /**
     * 用户登录
     * @userRegVo 用户数据：用户名、密码、登陆ip、地址
     * @return
     */
    @RequestMapping("/login")
    public String login(UserRegisterVo userRegisterVo,RedirectAttributes attributes, HttpSession session) {
        String password = userRegisterVo.getPassword();
        String user = userRegisterVo.getUserName();
        //手机号正则表达式
        Pattern phone = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");
        //邮箱正则表达式
        Pattern email = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
        //传入的参数
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setPassword(password);
        //查询出的用户
        MemberVo getMember = new MemberVo();
        if(phone.matcher(user).matches()){//通过手机号匹配用户
            memberEntity.setMobile(user);
            getMember = memberService.getUserMobile(memberEntity).getData(new TypeReference<MemberVo>(){});
        }else if(email.matcher(user).matches()){//使用邮箱匹配用户
            memberEntity.setEmail(user);
            getMember = memberService.getUserEmail(memberEntity).getData(new TypeReference<MemberVo>(){});
        }else{//使用用户名匹配用户
            memberEntity.setUsername(user);
            getMember = memberService.getUserName(memberEntity).getData(new TypeReference<MemberVo>(){});
        }
        //获取到数据库里的password
        String password1 = memberEntity.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //进行密码匹配
        if(password.equals(password1)&&getMember.getStatus()==0){
            //添加用户登陆数据
            memberService.addmemberLoginLog(userRegisterVo);
            session.setAttribute(LOGIN_USER,getMember);
            return "redirect:http://localhost:10000/index.html";
        }else{
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",getMember.toString());
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://localhost:20000/login.html";
        }
    }

    @GetMapping(value = "/loguot.html")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute(LOGIN_USER);
        request.getSession().invalidate();
        return "redirect:http://localhost:10000/index.html";
    }

//    /**
//     * 生成随机数
//     * @param max 随机数的位数
//     * @return
//     */
//    public String random(int max){
//        String random = "";
//        Random r = new Random();
//        for (int i = 0; i < max; i++) {
//            int ran1 = r.nextInt(10);
//            random += String.valueOf(ran1);
//        }
//        return random;
//    }

    /**
     * 判断用户名是否重复
     * @param name 用户名
     * @return 0重复，1不重复
     */
    @ResponseBody
    @GetMapping("/getUserName")
    public R getUserName(String name){
        Map<String,Object> map = new HashMap<>();
        //传入的参数
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setUsername(name);
        MemberEntity member = memberService.getUserName(memberEntity).getData(new TypeReference<MemberEntity>(){});
        if(member!=null&&member.getStatus()<=1){
            return R.error(0,"该用户名已被注册");
        }else{
            map.put("code",1);
            return R.ok(map);
        }
    }

    /**
     * 判断手机号是否重复
     * @param phone 手机号
     * @return 0重复，1不重复
     */
    @ResponseBody
    @GetMapping("/getUserPhone")
    public R getUserPhone(String phone){
        Map<String,Object> map = new HashMap<>();
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setMobile(phone);
        MemberEntity member = memberService.getUserMobile(memberEntity).getData(new TypeReference<MemberEntity>(){});
        if(member!=null&&member.getStatus()<=1){
            return R.error(0,"该手机号已被注册");
        }else{
            map.put("code",1);
            return R.ok(map);
        }
    }

}
